package com.example.filelock.fragment;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnticipateInterpolator;
import android.view.animation.BounceInterpolator;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.example.filelock.MainActivity;
import com.example.filelock.R;
import com.example.filelock.entity.FileViewEntity;
import com.example.filelock.utils.BasDataUtil;
import com.example.filelock.utils.FileUtil;
import com.example.filelock.utils.FileZipUtil;
import com.example.filelock.utils.LoadingFile;
import com.example.filelock.utils.LogOnFileItem;
import com.example.filelock.utils.PageViewUitl;
import com.rey.material.app.BottomSheetDialog;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import static com.example.filelock.utils.FileUtil.getFileNameEnd;

public class EncryptionFragment extends Fragment {
    private View view;
    private ListView mEncryptionLvFileList;
    private ImageView mEncryptionIvAdd;
    private String returnPath;
    private List<FileViewEntity> fileViewEntities;
    private FileLayoutViewAdapter fileLayoutViewAdapter;
    private SwipeRefreshLayout mEncryptionLayoutRefresh;
    private BottomSheetDialog bottomSheetDialog;
    private LinearLayout mEncryptionLayoutDeletes;
    private TextView mEncryptionTvAllSt;
    private TextView mEncryptionTvNotAllSt;
    private TextView mEncryptionTvDtReturn;
    private TextView mEncryptionTvDelete;
    private TextView mEncryptionTvShareFiles;
    private boolean isItemSelectView = false;   //是否处于删除状态
    private boolean isAddIconAlp;
    private long firstTime = 0;


    @Override
    public void onResume() {
        updateFileView();//刷新文件
        super.onResume();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.activity_encryption_fragment, container, false);
        intiView();
        setView();
        onclick();
        return view;
    }

    private void onclick() {
//        点击加密文件
        mEncryptionIvAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //点击选择文件
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("*/*");//无类型限制
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                startActivityForResult(intent, 1);
            }
        });
//        点击屏幕
        mEncryptionIvAdd.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                isAddIconAlp = !isAddIconAlp;
                mEncryptionIvAdd.setAlpha(isAddIconAlp ? (float) 0.2 :1);
                return  true;
            }
        });
    }
    private void setView() {
        mEncryptionLayoutRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //刷新获取文件
                updateFileView();
            }
        });
//        点击list
        mEncryptionLvFileList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    LogOnFileItem logOnFileItem = new LogOnFileItem(getContext());
                    logOnFileItem.onItemFileSet(fileViewEntities.get(position), true);
                    logOnFileItem.addLogCompete(new LogOnFileItem.LogCompete() {
                        @Override
                        public void onDeleteCompete() {
                            updateFileView();
                            Toast.makeText(getContext(), "删除成功", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onLoadingOkCompete() {
                            try {
                                if (MainActivity.mMainLayoutVp!=null)
                                    MainActivity.mMainLayoutVp.setCurrentItem(2);
                                if (DecryptionFragment.mDecryptionLayoutRefresh!=null&&DecryptionFragment.fileViewEntities!=null&&DecryptionFragment.fileLayoutViewAdapter!=null)
                                    DecryptionFragment.updateFileView(getContext());
                            }catch (Exception e){
                                Log.d(BasDataUtil.LOG_TOAST,"强行刷新解密页面错误:"+e.toString());
                            }

                        }
                    });
                }catch (Exception e){
                    Log.d(BasDataUtil.LOG_TOAST,"加密页面加密错误："+e.toString());
                }

            }
        });
//        长安删除
        mEncryptionLvFileList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//                显示选择删除
                for (int i = 0; i < fileViewEntities.size(); i++) {
                    fileViewEntities.get(i).setViewSelect(true);
                    fileViewEntities.set(i, fileViewEntities.get(i));
                }
                fileLayoutViewAdapter.notifyDataSetChanged();
//                消失筛选
                mEncryptionLayoutDeletes.setVisibility(View.VISIBLE);
//                修改状态:处于删除状态
                isItemSelectView = true;
                return false;
            }
        });
//        退出删除模式
        mEncryptionTvDtReturn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    //                消失选择删除
                    for (int i = 0; i < fileViewEntities.size(); i++) {
                        fileViewEntities.get(i).setViewSelect(false);
                        fileViewEntities.set(i, fileViewEntities.get(i));
                    }
                    fileLayoutViewAdapter.notifyDataSetChanged();
                    mEncryptionLayoutDeletes.setVisibility(View.GONE);
                    //                修改状态:不处于删除状态
                    isItemSelectView = false;
                }catch (Exception e){}

            }
        });
//        全选
        mEncryptionTvAllSt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < fileViewEntities.size(); i++) {
                    fileViewEntities.get(i).setSelect(true);
                    fileViewEntities.set(i, fileViewEntities.get(i));
                }
                fileLayoutViewAdapter.notifyDataSetChanged();
            }
        });
//        全不选
        mEncryptionTvNotAllSt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < fileViewEntities.size(); i++) {
                    fileViewEntities.get(i).setSelect(false);
                    fileViewEntities.set(i, fileViewEntities.get(i));
                }
                fileLayoutViewAdapter.notifyDataSetChanged();
            }
        });
//        删除勾选
        mEncryptionTvDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    int deleteContent = 0;
                    for (int i = 0; i < fileViewEntities.size(); i++) {
                        if (fileViewEntities.get(i).isSelect()) {
                            //删除勾选
                            FileUtil.deleteFile(fileViewEntities.get(i).getFilePath(), getContext());
                            deleteContent++;
                        }
                    }
                    if (deleteContent!=0){
                        updateFileView();
                        Toast.makeText(getContext(), "删除成功", Toast.LENGTH_SHORT).show();
                    }

                }catch (Exception e){
                    Log.d(BasDataUtil.LOG_TOAST,"加密页面输出勾选错误:"+e.toString());
                }

            }
        });
//        分享发送勾选
        mEncryptionTvShareFiles.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    ArrayList<Uri> files = new ArrayList<Uri>();
                    for (int i = 0; i < fileViewEntities.size(); i++) {
                        if (fileViewEntities.get(i).isSelect()) {
                            File file = new File(fileViewEntities.get(i).getFilePath());
                            if (file.exists())
                                files.add(Uri.fromFile(file));
                        }
                    }
                    if (files.size()!=0){
                        //分享文件
                        Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);//发送多个文件
                        intent.setType("*/*");//多个文件格式
                        intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, files);//Intent.EXTRA_STREAM同于传输文件流
                        startActivity(intent);
                    }
                }catch (Exception e){
                    Log.d(BasDataUtil.LOG_TOAST,"分享多个文件错误："+e.toString());
                }


            }
        });
    }

    private void updateFileView() {
        try {
            //获取文件里所有文件
            fileViewEntities = new ArrayList<>();
            String path = BasDataUtil.getEncryptionPath();
            File file = new File(path);
            File[] files = file.listFiles();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            for (int i = 0; i < files.length; i++) {
                if (FileUtil.getFileNameEnd(files[i].getName()).equals(".t")) {
                    FileViewEntity fileViewEntity = new FileViewEntity();
                    fileViewEntity.setFileEnd(FileUtil.getFileNameEnd(files[i].getName()));
                    fileViewEntity.setFileName(files[i].getName());
                    fileViewEntity.setFileMsg(String.format("%.2f", (double) files[i].length() / 1000000) + "m | " + dateFormat.format(files[i].lastModified()));
                    fileViewEntity.setFilePath(files[i].getPath());
                    fileViewEntity.setSelect(false);
                    fileViewEntity.setViewSelect(isItemSelectView);
                    fileViewEntities.add(fileViewEntity);
                }
            }
            fileLayoutViewAdapter.notifyDataSetChanged();
            mEncryptionLayoutRefresh.setRefreshing(false);
        } catch (Exception e) {
            Log.d(BasDataUtil.LOG_TOAST, "加密页刷新错误:" + e.toString());
            //        初始化文件夹
            FileUtil.initMainFile(getContext());
            mEncryptionLayoutRefresh.setRefreshing(false);
        }


    }

    private void intiView() {
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();
        mEncryptionLvFileList = view.findViewById(R.id.encryption_lv_fileList);
        mEncryptionIvAdd = view.findViewById(R.id.encryption_iv_add);
        mEncryptionLayoutRefresh = view.findViewById(R.id.encryption_layout_refresh);
        mEncryptionLayoutDeletes = view.findViewById(R.id.encryption_layout_deletes);
        mEncryptionTvAllSt = view.findViewById(R.id.encryption_tv_allSt);
        mEncryptionTvNotAllSt = view.findViewById(R.id.encryption_tv_notAllSt);
        mEncryptionTvDtReturn = view.findViewById(R.id.encryption_tv_DtReturn);
        mEncryptionTvDelete = view.findViewById(R.id.encryption_tv_delete);
        mEncryptionTvShareFiles = view.findViewById(R.id.encryption_tv_shareFiles);
        fileViewEntities = new ArrayList<>();
        fileLayoutViewAdapter = new FileLayoutViewAdapter();
        mEncryptionLvFileList.setAdapter(fileLayoutViewAdapter);
        mEncryptionLayoutRefresh.setColorSchemeColors(getResources().getColor(R.color.mainColor));
//        适配listview和swipeRefreshLayout
        PageViewUitl.adapterLS(mEncryptionLvFileList, mEncryptionLayoutRefresh);
    }
//    选择文件的回调

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            returnPath = "";
            Uri uri = data.getData();
            if ("file".equalsIgnoreCase(uri.getScheme())) {//使用第三方应用打开
                returnPath = uri.getPath();
                return;
            }
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {//4.4以后
                returnPath = FileUtil.getPath(getContext(), uri);

            } else {//4.4以下下系统调用方法
                returnPath = FileUtil.getRealPathFromURI(uri);
            }
            if (returnPath != null && !returnPath.equals("")) {
                final View logView = LayoutInflater.from(getContext()).inflate(R.layout.log_decryption_view, null);
                final EditText ev_pwd = logView.findViewById(R.id.log_encryption_et_pwd);
                AlertDialog alertDialog = new AlertDialog.Builder(getContext())
                        .setTitle("加密文件")
                        .setView(logView)
                        .setNegativeButton("取消", null)
                        .setPositiveButton("加密", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                try {
                                    //点击加密，获取组件
                                    //弹出加载对话框
                                    final String path = returnPath;
                                    String s_pwd = ev_pwd.getText().toString();
                                    if (s_pwd.equals("")) {
                                        Toast.makeText(getContext(), "不能为空!", Toast.LENGTH_SHORT).show();
                                    } else if (s_pwd.length() < 3 || s_pwd.length() > 6) {
                                        Toast.makeText(getContext(), "密码长度不符合!", Toast.LENGTH_SHORT).show();
                                    } else {

                                        final long fileLength = new File(path).length();
                                        LoadingFile loadingFile = new LoadingFile(getContext(), fileLength);
                                        if (!loadingFile.encryptionFile(path, s_pwd)) {
                                            Toast.makeText(getContext(), "文件为空", Toast.LENGTH_SHORT).show();
                                        }
//                                    加载完成回调
                                        loadingFile.addLoadingOk(new LoadingFile.LoadingFileOk() {
                                            @Override
                                            public void onLoadingOk() {
                                                updateFileView();
                                            }
                                        });
                                    }
                                }catch (Exception e){
                                    Log.d(BasDataUtil.LOG_TOAST,"加密页面回调文件加密错误:"+e.toString());
                                }


                            }
                        })
                        .show();
            }
        }
    }

    //    适配器
    public class FileLayoutViewAdapter extends BaseAdapter {


        @Override
        public int getCount() {
            return fileViewEntities.size();
        }

        @Override
        public FileViewEntity getItem(int position) {
            return fileViewEntities.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.file_layout_view, null);
                convertView.setTag(new ViewHolder(convertView));
            }
            initializeViews((FileViewEntity) getItem(position), (ViewHolder) convertView.getTag(), position);
            return convertView;
        }

        private void initializeViews(final FileViewEntity object, final ViewHolder holder, final int position) {
            //TODO implement
            holder.fileViewTvFileName.setText(object.getFileName());
            holder.fileViewTvMsg.setText(object.getFileMsg());
            if (object.isViewSelect()) {
                holder.fileViewRBtSelect.setVisibility(View.VISIBLE);
            } else {
                holder.fileViewRBtSelect.setVisibility(View.GONE);
            }

            holder.fileViewRBtSelect.setChecked(object.isSelect());
            if (object.getFileEnd() != null) {
                int i = getContext().getResources().getIdentifier(getContext().getPackageName() + ":drawable/file_icon_" + FileUtil.getFileNameEedQ(object.getFileEnd()),
                        null, null);
                if (i == 0)
                    holder.fileViewImg.setImageResource(R.drawable.file_icon_default);
                else
                    holder.fileViewImg.setImageResource(i);
            }
            holder.fileViewRBtSelect.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    object.setSelect(holder.fileViewRBtSelect.isChecked());
                    fileViewEntities.set(position, object);
                }
            });
        }

        protected class ViewHolder {
            private TextView fileViewTvFileName;
            private TextView fileViewTvMsg;
            private CheckBox fileViewRBtSelect;
            private ImageView fileViewImg;

            public ViewHolder(View view) {
                fileViewTvFileName = (TextView) view.findViewById(R.id.fileView_tv_fileName);
                fileViewTvMsg = (TextView) view.findViewById(R.id.fileView_tv_msg);
                fileViewRBtSelect = view.findViewById(R.id.fileView_cbt_select);
                fileViewImg = view.findViewById(R.id.fileView_iv_img);
            }
        }
    }


}
